package com.nobrain.uboard.fragment;

import java.util.ArrayList;

import com.nobrain.uboard.act.MainAct;
import com.nobrain.uboard.act.R;
import com.nobrain.uboard.observer.IObserver;
import com.nobrain.uboard.observer.ObserverManager;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;

public class MainAct_Services extends Fragment implements IObserver{
	private GridView gv;
	private ArrayList<String> list;
	private ArrayAdapter<String> adapter;
	
	private final int WHAT_GRIDUPDATE = 0;
	private AsyncTask<Void, Void, Void> task;
	
	private OnItemChangeListener l = new OnItemChangeListener() {
		
		@Override
		public void delItem(int i) {
			
			try{
				list.remove(i);
			} catch (NullPointerException e){}
			mHandler.sendEmptyMessage(WHAT_GRIDUPDATE);
		}
		
		@Override
		public void addItem(String s) {
			list.add(s);
			mHandler.sendEmptyMessage(WHAT_GRIDUPDATE);
		}
	};
	
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what){
			case WHAT_GRIDUPDATE:
				adapter.notifyDataSetChanged();
				break;
			}
		}
		
	};
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.mainact_services, null);
		gv = (GridView) v.findViewById(R.id.gv_main_services);
		return v;
	}

	@Override
	public void onStart() {
		super.onStart();
		list = new ArrayList<String>();
		adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,list);
		
		gv.setAdapter(adapter);
		
		FragmentActivity act = getActivity();
		if(act instanceof MainAct){
			((MainAct) act).setOnItemChangeListener(l);
			
		}
	}

	
	public interface OnItemChangeListener{
		public void addItem(String s);
		public void delItem(int i);
	}

	
	void excuteData(){
		if(task != null && task.getStatus() == AsyncTask.Status.RUNNING){
			task.cancel(true);
		}
		task = new AsyncTask<Void, Void, Void>(){

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
			}

			@Override
			protected Void doInBackground(Void... params) {
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
			}
			
		};
	}

	@Override
	public void update(int type) {
		if(type == ObserverManager.TYPE_MAIN_SERVICES){
			adapter.notifyDataSetChanged();
		}
	}
}
